package com.jsgt.greekfire.common.util

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import com.jsgt.greekfire.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * 截图视图
 */
object ViewCapture {
    fun getViewBitmap(view: View?): Bitmap? {
        if (view == null) {
            return null
        }
        val bitmap = Bitmap.createBitmap(
            view.width,
            view.height,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        val bgDrawable = view.background
        canvas.drawColor(Color.WHITE) // 默认为白色背景
        bgDrawable?.draw(canvas)
        view.draw(canvas)
        return bitmap
    }

    //保存文件到指定路径
    fun saveImageToGallery(
        context: Context,
        bmp: Bitmap?
    ): Boolean {
        if (bmp == null){
            return false
        }
        var appDir:File ?= null
        // 首先保存图片
        appDir = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){
            val storePath = Environment.getExternalStorageDirectory()
                .absolutePath + File.separator + context.getString(R.string.app_name)
            File(storePath)
        }else {
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        }
        if (!appDir!!.exists()) {
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            //通过io流的方式来压缩保存图片
            val isSuccess =
                bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos)
            fos.flush()
            fos.close()

            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(
                context.contentResolver,
                file.absolutePath,
                fileName,
                null
            )

            //保存图片后发送广播通知更新数据库
            val uri = Uri.fromFile(file)
            context.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    uri
                )
            )
            return isSuccess
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return false
    }
}